<template>
  <div class="app-container">
    <div class="top">
      <div class="operate">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['taskMgmt:configuration:add']"
          >新增
        </el-button>
        <el-button
          icon="el-icon-edit"
          size="mini"
          :disabled="single != true"
          @click="handleUpdate()"
          v-hasPermi="['taskMgmt:configuration:edit']"
          >编辑
        </el-button>
        <el-button
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['taskMgmt:configuration:export']"
          >导出
        </el-button>
      </div>
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        label-width="68px"
      >
        <el-form-item prop="taskName" class="width1">
          <el-input
            v-model="queryParams.taskName"
            placeholder="请输入关键字"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <organizationCascader
          class="organization-cascader"
          :clearData="{
            factory: true,
            workshop: true,
            line: true,
          }"
          :arrData="queryParams"
          :showData="{
            factory: true,
            workshop: true,
            line: true,
            workSection: false,
          }"
          :isAllList="true"
          @change="queryParamsChange"
        ></organizationCascader>
        <el-form-item prop="taskType" class="width1">
          <el-select
            v-model="queryParams.taskType"
            placeholder="请选择任务类型"
            clearable
            size="small"
          >
            <el-option
              v-for="item in dict.taskType"
              :key="item.codevalue"
              :label="item.codename"
              :value="item.codevalue"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="status" class="width1">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            clearable
            size="small"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.codevalue"
              :label="item.codename"
              :value="item.codevalue"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <el-table
      ref="Table"
      :data="list"
      tooltip-effect="dark"
      style="width: 100%"
      height="calc(100% - 44px - 50px)"
      v-loading="loading"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column label="任务配置名称" prop="taskName" min-width="150">
        <template slot-scope="{ row }">
          <el-button type="text" @click.stop="handleShowDetail(row)">{{
            row.taskName
          }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="任务类型" prop="taskType" width="140">
        <template slot-scope="{ row }">
          {{ taskTypeOptionsMap[row.taskType] }}
        </template>
      </el-table-column>
      <el-table-column label="任务性质" prop="taskNature" width="120">
        <template slot-scope="{ row }">
          {{ taskNatureOptionsMap[row.taskNature] }}
        </template>
      </el-table-column>
      <el-table-column
        label="是否品控关注任务"
        prop="isConcernedTask"
        width="130"
      >
        <template slot-scope="{ row }">
          {{ row.isConcernedTask == "1" ? "是" : "否" }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="所属工厂" prop="ownedFactoryName">
      </el-table-column> -->
      <el-table-column label="车间" prop="ownedWorkshopName"> </el-table-column>
      <el-table-column label="产线" prop="ownedProductionLineName" width="150">
      </el-table-column>
      <el-table-column label="执行人">
        <template slot-scope="{ row }">
          {{ getOperatorName(row) }}
        </template>
      </el-table-column>
      <el-table-column label="审核人" prop="auditorName"> </el-table-column>
      <el-table-column label="执行周期" width="120">
        <template slot-scope="{ row }">
          <span v-if="row.taskNature == '1'">
            {{
              ["1", "7"].includes(row.taskType)
                ? "接班时下发任务"
                : `每${row.frequency + row.taskFrequencyName}执行1次`
            }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="执行时间" prop="executeStartTime" width="160">
        <!-- 周期性任务，若频次选择“月”，则“生效时间”提供时间（年月日）组件； -->
        <template slot-scope="{ row }">
          <span v-if="row.taskNature == '1' && row.taskFrequency == '3'">
            {{ parseTime(row.executeStartTime, "{h}:{i}:{s}") }}至{{
              parseTime(row.executeEndTime, "{h}:{i}:{s}")
            }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="生效时间" prop="effectiveDate" width="160">
        <template slot-scope="{ row }">
          {{ getEffectiveDate(row) }}
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="status">
        <template slot-scope="{ row }">
          {{ row.status == "1" ? "已启用" : "已停用" }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="130" fixed="right">
        <template slot-scope="{ row }">
          <el-button
            v-if="
              buttonPermi(
                ['taskMgmt:configuration:deactivate'],
                row.status == '1'
              )
            "
            type="text"
            @click.stop="handleDeactivate(row)"
            >停用</el-button
          >
          <el-button
            v-if="
              buttonPermi(
                ['taskMgmt:configuration:activate'],
                row.status == '0'
              )
            "
            type="text"
            @click.stop="handleActivate(row)"
            >启用</el-button
          >
          <el-button
            v-if="buttonPermi(['taskMgmt:configuration:edit'], true)"
            type="text"
            @click.stop="handleUpdate(row)"
            >编辑</el-button
          >
          <!-- 启用状态的任务配置，不允许删除，禁用状态的才可以删除 -->
          <el-button
            v-if="
              buttonPermi(['taskMgmt:configuration:remove'], row.status == '0')
            "
            type="text"
            @click.stop="handleDelete(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      :total="pager.total"
      :page.sync="pager.pageNum"
      :limit.sync="pager.pageSize"
      @pagination="getList"
    />

    <DetailDialog
      :visible.sync="detailDialog.visible"
      :row="detailDialog.row"
      :disabled="detailDialog.disabled"
      @refresh="getList"
    ></DetailDialog>
  </div>
</template>
<script>
import organizationCascader from "@/views/components/organizationCascader";
import DetailDialog from "./detailDialog";
import { checkPermi } from "@/utils/permission";
import {
  getTaskConfigList,
  saveTaskConfig,
  deleteTaskConfig,
  exportTaskConfig,
} from "@/api/taskMgmt/configuration";
import { downloadFile } from "@/utils/file";
export default {
  name: "Configuration",
  components: { organizationCascader, DetailDialog },
  dicts: ["taskNature", "taskType", "PostManage"],
  data() {
    return {
      queryParams: {
        taskName: "",
        factoryDeptCode: "",
        workshopCode: "",
        lineCode: "",
        lineId: "",
        taskType: "",
        status: "",
      },
      statusOptions: [
        {
          codevalue: "1",
          codename: "已启用",
        },
        {
          codevalue: "0",
          codename: "已停用",
        },
      ],
      list: [],
      single: null,
      loading: false,
      pager: {
        total: 0,
        pageNum: 1,
        pageSize: 10,
      },
      exportLoading: false,
      detailDialog: {
        visible: false,
        row: null,
        disabled: false,
      },
    };
  },
  computed: {
    taskTypeOptionsMap() {
      return this.dictToMap(this.dict.taskType);
    },
    taskNatureOptionsMap() {
      return this.dictToMap(this.dict.taskNature);
    },
    postManageDictObj() {
      return this.dictToMap(this.dict.PostManage);
    },
  },
  created() {
    // 默认获取第一个工厂
    const results = this.getOwnFirstLine();
    this.queryParams.factoryDeptCode = results[0]?.factoryDeptCode || "";
    this.queryParams.workshopCode = results[1]?.workshopCode || "";
    this.queryParams.lineCode = results[2]?.lineCode || "";
    this.queryParams.lineId = results[2]?.lineId || "";
    //获取列表数据
    this.getList();
  },
  methods: {
    // 列表按钮显示权限
    buttonPermi(permis, flag) {
      return checkPermi(permis) && flag;
    },
    getList() {
      this.loading = true;
      this.single = null;
      const { pageNum, pageSize } = this.pager;
      const {
        taskName,
        factoryDeptCode,
        workshopCode,
        lineCode,
        taskType,
        status,
      } = this.queryParams;
      const params = {
        query: {
          taskName,
          ownedFactory: factoryDeptCode,
          ownedWorkshop: workshopCode,
          ownedProductionLine: lineCode,
          taskType,
          status,
        },
        pageNum,
        pageSize,
      };
      getTaskConfigList(params)
        .then((res) => {
          this.list = res.rows || [];
          this.pager.total = res.total;
          this.loading = false;
        })
        .catch(() => {
          this.list = [];
          this.pager.total = 0;
          this.loading = false;
        });
    },
    handleSelectionChange(selection) {
      if (selection.length > 1) {
        this.single = false;
      } else if (selection.length == 1) {
        this.single = true;
      } else {
        this.single = null;
      }
    },
    queryParamsChange({ factoryDeptCode, workshopCode, lineCode, lineId }) {
      this.queryParams.factoryDeptCode = factoryDeptCode;
      this.queryParams.workshopCode = workshopCode;
      this.queryParams.lineCode = lineCode;
      this.queryParams.lineId = lineId;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.pager.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        taskName: "",
        factoryDeptCode: "",
        workshopCode: "",
        lineCode: "",
        lineId: "",
        taskType: "",
        status: "",
      };
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.detailDialog.row = null;
      this.detailDialog.visible = true;
      this.detailDialog.disabled = false;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      if (!row) {
        row = this.$refs.Table.selection[0] || null;
      }
      this.detailDialog.row = row;
      this.detailDialog.visible = true;
      this.detailDialog.disabled = false;
    },
    /** 查看详情按钮操作 */
    handleShowDetail(row) {
      this.detailDialog.row = row;
      this.detailDialog.visible = true;
      this.detailDialog.disabled = true;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      // 禁用状态才可以删除
      if (row.status != "0") {
        this.msgWarning("启用状态的任务配置不允许删除！");
        return;
      }
      let ids = "";
      let msg = "";
      if (row) {
        ids = row.id;
        msg = `确定删除${row.taskName}吗？(执行开始时间为次日及之后的任务将删除，不会继续生成。)`;
      } else {
        const selection = this.$refs.Table.selection;
        ids = selection.map((ele) => ele.id).join(",");
        msg = `确定删除所选的${selection.length}条记录吗？`;
      }
      this.$confirm(msg, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return deleteTaskConfig(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 停用按钮操作 */
    handleDeactivate(row) {
      this.$confirm(`确定停用${row.taskName}吗？`, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          const param = {
            id: row.id,
            status: "0",
          };
          return saveTaskConfig(param);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("操作成功");
        });
    },
    /** 启用按钮操作 */
    handleActivate(row) {
      this.$confirm(`确定启用${row.taskName}吗？`, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          const param = {
            id: row.id,
            status: "1",
          };
          return saveTaskConfig(param);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("操作成功");
        });
    },
    getOperatorName(row) {
      // 显示部门
      if (row.operatorType == "dept") {
        return row.executiveAgencyName || row.executiveAgency;
      }

      let operatorName = row.operatorName;

      // if (this.postManageDictObj.hasOwnProperty(row.operator)) {
      //   // 显示岗位
      //   operatorName = this.postManageDictObj[row.operator];
      // } else {
      //   // 显示工位
      //   operatorName = row.operatorName;
      // }

      return operatorName || "";
    },
    getEffectiveDate(row) {
      if (["3"].includes(row.taskFrequency)) {
        // 频次是月单位
        return row.effectiveDate
          ? row.effectiveDate.replace(" 00:00:00", "")
          : "";
      }
      return row.effectiveDate;
    },
    handleExport() {
      this.exportLoading = true;
      const {
        taskName,
        factoryDeptCode,
        workshopCode,
        lineCode,
        taskType,
        status,
      } = this.queryParams;
      const params = {
        taskName,
        ownedFactory: factoryDeptCode,
        ownedWorkshop: workshopCode,
        ownedProductionLine: lineCode,
        taskType,
        status,
      };
      exportTaskConfig(params)
        .then((res) => {
          downloadFile(
            res.file,
            res.name ||
              `任务配置列表${this.parseTime(new Date(), "{y}{m}{d}")}.xlsx`
          );
        })
        .finally(() => {
          this.exportLoading = false;
        });
    },
  },
};
</script>
<style lang="scss" scoped>
.top {
  height: 44px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}
.pagination-container {
  margin: 0;
}
::v-deep .organization-cascader {
  display: inline-block;
  vertical-align: middle;
  color: #cccccc;
  .el-form-item {
    margin-bottom: 0;
    .el-form-item__content {
      width: 154px;
    }
  }
}
::v-deep .width1 {
  .el-form-item__content {
    width: 154px;
  }
}
</style>
